;
(function () {
'use strict';

/**
 * @ngdoc service
 * @name LoginServer
 * @description
 */
angular.module('services.login',[])
  .service('servicesLogin',servicesLogin)
  .factory('LoginServer', loginServer);
function servicesLogin(){
  this.clickIf = {clickIf:false};
}

function loginServer(Restangular, $state, $mdDialog, $cookies, CoreService, $timeout,servicesLogin) {
  var login = Restangular.all('sas/login');
  var logout =  Restangular.all('sas/signOut');
  return {
    loginCheck: loginCheck,
    signOut: signOut
  };
  /**
   * 用户登录service
   * @param user
   */
  function loginCheck(user) {
    if (user.userName === '' ) {
      CoreService.dialog('请输入用户名');
      servicesLogin.clickIf.clickIf = false;
      return;
    }
    //5秒内后台没反应，登录按钮置灰
    $timeout(function(){servicesLogin.clickIf.clickIf = false;},5000);
    login.post(user).then(success, error);

    function success(res) {
      if (res.state === '10000') {
        servicesLogin.clickIf.clickIf = true;
        $cookies.putObject('userCookie', res.data);
        $state.go('sas.omdisplay');
      } else {
        CoreService.dialog(res.state);
        servicesLogin.clickIf.clickIf = false;
      }
    }
    function error() {
      $mdDialog.show(
        $mdDialog
          .alert()
          .title('错误')
          .content('连接服务器失败，请稍后重试')
          .ok('关闭')
      );
      servicesLogin.clickIf.clickIf = false;
    }
  }

  /**
   * 退出登录
   * @param userId 用户id
   */
  function signOut(userId) {
    servicesLogin.clickIf.clickIf = false;
    logout.post(userId).then(success);
    function success(res) {
      if (res.state === '10000') {
        $cookies.remove('userCookie');
        $state.go('login');
      } else {
        CoreService.dialog(res.state, '提示(' + res.state + ')');
      }
    }
  }

}
})();